package com.justech.tcp.server.parse;


/**
 * @author feifei.li
 */
public class EquipmentInfoParser implements Parser {

    static final class VarIndex {
        public static final int EQUIPMENT_NAME = 0;
        public static final int SN = 1;
        public static final int DATA_TYPE = 2;
        public static final int INDEX = 3;
        public static final int LENGTH = 4;
    }

    static final String START = "Start";
    static final String END = "End@";

    public EquipmentInfo parse(String str) throws ParserException {
        /*
        B3i,E-19001,3,1,32,Start,CCD1,12.03,15.32,End@
        */
        String[] paragraph = str.split(",");
        String equipmentName = paragraph[VarIndex.EQUIPMENT_NAME];
        String sn = paragraph[VarIndex.SN];
        String dataType = paragraph[VarIndex.DATA_TYPE];
        String index = paragraph[VarIndex.INDEX];
        String length = paragraph[VarIndex.LENGTH];

        StringArrayList<Object> data = parseData(paragraph, dataType);
        EquipmentInfo equipmentInfo = new EquipmentInfo();
        equipmentInfo.setEquipmentName(equipmentName);
        equipmentInfo.setSn(sn);
        equipmentInfo.setDataType(dataType);
        equipmentInfo.setIndex(Integer.parseInt(index));
        equipmentInfo.setLength(Integer.parseInt(length));
        equipmentInfo.setData(data);
        return equipmentInfo;
    }

    private StringArrayList<Object> parseData(String[] paragraph, String dataType) {
        StringArrayList<Object> doubles = new StringArrayList<Object>();
        for (int i = 0; i < paragraph.length; i++) {
            String p = paragraph[i];
            if (i > 5 && i < (paragraph.length - 1)) {
                doubles.add(p);
            }
        }
        if (!dataType.equals(String.valueOf(VarIndex.SN))) {
            if (doubles.size() <= VarIndex.DATA_TYPE) {
                return doubles;
            } else {
                throw new RuntimeException("参数错误");
            }
        }
        return doubles;
    }
}
